package ntrees.hu.renren;

import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import com.cooliris.picasa.Entry;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;

/*
 * 1.目前只支持单用户登录。
 * 2.删除帐户后应该删除缓存数据
 * 3.添加用户后应该自动进行同步数据。
 * 4.帐户处应该显示用户名而非id
 * */

public class RenrenApi {
	
	private static final String TAG = "RenrenApi";
    
	public static final int RESULT_OK = 0;
    public static final int RESULT_NOT_MODIFIED = 1;
    public static final int RESULT_ERROR = 2;
    
	private static final String API_KEY = "b2585844587c491f89a5303ac23a119d";
	private static final String SECRET_KEY = "3dcdaebbaac341f880bd0e7ab0263778";
	private static final String APP_ID = "169705";

	AccessTokenManager mAccessTokenManager;
	void init(Context ctx) {
		mAccessTokenManager = new AccessTokenManager(ctx);
		if (mAccessTokenManager.isSessionKeyValid()) {
			Log.d(TAG, "isSessionKeyValid");
		}
	}
	
	RenrenApi(Context context) {
		init(context);
	}
	
	private final String BASE_URL = "http://api.renren.com/restserver.do";
    
    void getAlbums(RenrenUserEntry user, EntryHandler handler) {
    	Log.d(TAG, "user: " + user);
    	Bundle params = new Bundle();
		params.putString("method", "photos.getAlbums");
		String uid;
		if (user != null)
			uid = String.valueOf(user.uid);
		else
			uid = String.valueOf(mAccessTokenManager.getUid());
		params.putString("uid", String.valueOf(mAccessTokenManager.getUid()));
    	String response = requestJSON(params);
    	Log.d(TAG, response);
    	AlbumGetResponseBean bean = new AlbumGetResponseBean(response);
    	List<RenrenAlbumEntry> albums = bean.getAlbums();
    	for (RenrenAlbumEntry entry: albums) {
    		handler.handleEntry(entry);
    	}
    }
    
    void getAlbumPhotos(RenrenAlbumEntry album, EntryHandler handler) {
    	Bundle params = new Bundle();
		params.putString("method", "photos.get");
		params.putString("uid", String.valueOf(album.uid));
		params.putString("aid", String.valueOf(album.aid));
    	String response = requestJSON(params);
    	//Log.d(TAG, response);
    	PhotoGetResponseBean bean = new PhotoGetResponseBean(response);
    	List<RenrenPhotoEntry> photos = bean.getPhotos();
    	for (RenrenPhotoEntry entry: photos) {
    		handler.handleEntry(entry);
    	}
    }
    
    public String requestJSON(Bundle parameters) {
    	Log.d(TAG, "requestJSON");
		return this.request(parameters, "json");
	}
    
	private String request(Bundle parameters, String format) {
    	Log.d(TAG, "request");
		parameters.putString("format", format);
		if (isSessionKeyValid()) {
			parameters.putString("session_key", mAccessTokenManager.getSessionKey());
		}
		
		this.prepareParams(parameters);
		//logRequest(parameters);
		String response = Util.openUrl(BASE_URL, "POST", parameters);
		//logResponse(parameters.getString("method"), response);
		return response;
	}
    
	private void prepareParams(Bundle params) {
    	Log.d(TAG, "prepareParams");
		params.putString("api_key", API_KEY);
		params.putString("v", "1.0");
		params.putString("call_id", String.valueOf(System.currentTimeMillis()));
		params.putString("xn_ss", "1");// sessionSecret作为加密密钥

		StringBuffer sb = new StringBuffer();
		Set<String> keys = new TreeSet<String>(params.keySet());
		for (String key : keys) {
			sb.append(key);
			sb.append("=");
			sb.append(params.getString(key));
		}
		sb.append(mAccessTokenManager.getSessionSecret());
		params.putString("sig", Util.md5(sb.toString()));
	}
	
	/**
	 * 记录请求log
	 */
	private void logRequest(Bundle params) {
		if(params != null) {
			String method = params.getString("method");
			if(method != null) {
				StringBuffer sb = new StringBuffer();
				sb.append("method=").append(method).append("&").append(params.toString());
				Log.i(TAG, sb.toString());
			} else {
				Log.i(TAG, params.toString());
			}
		}		
	}
	
	/**
	 * 记录响应log
	 * @param response
	 */
	private void logResponse(String method, String response) {
		if(method != null && response != null) {
			StringBuffer sb = new StringBuffer();
			sb.append("method=").append(method).append("&").append(response);
			Log.i(TAG, sb.toString());
		}
	}
	
	public boolean isSessionKeyValid() {
		return this.mAccessTokenManager.isSessionKeyValid();
	}
    
    public interface EntryHandler {
        void handleEntry(Entry entry);
    }
    
    public RenrenUserEntry getCurrentUser() {
    	RenrenUserEntry user = new RenrenUserEntry();
    	user.uid = mAccessTokenManager.getUid();
    	return user;
    }
}
